from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework_simplejwt.settings import api_settings
from djangoDrf.serializers import MyRefreshToken

from user.models import User
from django.contrib.auth.hashers import check_password


class UserView(GenericAPIView):

    queryset = User.objects.filter(is_delete=False)

    serializer_class = api_settings.TOKEN_OBTAIN_SERIALIZER

    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):

        username = request.data.get('username')
        password = request.data.get('password')

        queryset = self.get_queryset().filter(username=username)

        if not queryset:
            return Response({'detail': '用户名不正确'}, status=status.HTTP_401_UNAUTHORIZED)

        # 获取对应密码
        user = queryset[0]

        # 比较密码
        if not check_password(password, user.password):
            return Response({'detail': '密码不正确'}, status=status.HTTP_401_UNAUTHORIZED)

        # 判断当前账户是否激活
        if not user.is_active:
            return Response({'detail': '用户或密码不正确'}, status=status.HTTP_401_UNAUTHORIZED)

        # 返回令牌
        refresh = MyRefreshToken.for_user(user)

        data = {
            'refresh': str(refresh),
            'access': str(refresh.access_token),
        }

        return Response(data, status=status.HTTP_200_OK)